package com.net;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;
import java.net.SocketImpl;

/**
 * 查看Socket类
 * Created by yangliwei on 2017/7/19.
 */
public class SocketDemo {
    public static void main(String[] args) throws Exception {
        Socket socket = new Socket("127.0.0.1", 8888);

        byte[] wb = new byte[]{'c', 'w'};
        byte[] rb = new byte[16];

        getFD(socket);

        boolean flag =true;
        while(flag) {
            socket.getOutputStream().write(wb);
            Thread.sleep(2000);
        }
        socket.getInputStream().read(rb);
        System.out.println("server b " + rb[0]);

    }


    /**
     * 获取socket的文件描述符
     * @param socket
     * @throws Exception
     */
    public static void getFD(Socket socket)throws Exception{
        Field implField = Socket.class.getDeclaredField("impl");
        implField.setAccessible(true);
        SocketImpl socketImpl = (SocketImpl) implField.get(socket);

        Method method = SocketImpl.class.getDeclaredMethod("getFileDescriptor");
        method.setAccessible(true);
        FileDescriptor fd = (FileDescriptor)method.invoke(socketImpl);
        Field fdField = FileDescriptor.class.getDeclaredField("fd");
        fdField.setAccessible(true);
        System.out.println(fdField.get(fd));
    }


    //给socks设置代理
    @Test
    public void socksClient() {
        try {
            // proxy
            SocketAddress address = new InetSocketAddress("127.0.0.1", 6666);
            Proxy proxy = new Proxy(Proxy.Type.SOCKS, address);
//            Socket client = new Socket(proxy);

            //http
//            SocketAddress httpAddress = new InetSocketAddress("127.0.0.1", 8888);
//            Proxy httpProxy = new Proxy(Proxy.Type.HTTP, httpAddress);
            URL url = new URL("http://192.168.0.110:8080/vedios/test.html");

            URLConnection connection = url.openConnection(proxy);
            InputStream inputStream = connection.getInputStream();
            InputStreamReader reader = new InputStreamReader(inputStream);
            System.out.println(reader.getEncoding()+"  "+reader.read());
//            Socket httpClient = new Socket(httpProxy);



        }
        catch (IOException e) {
            e.printStackTrace();
        }

    }



}
